package com.zlsy.es.dianping.config;

import cn.hutool.core.collection.CollUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhouliang
 * @date 2020/03/09
 **/
@Slf4j
@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ElasticSearchRestClientConfig {

    private final ElasticSearchProperties elasticSearchProperties;

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        List<ElasticSearchProperties.EsAddress> addressList = elasticSearchProperties.getAddressList();
        if (CollUtil.isEmpty(addressList)) {
            log.error("ES的配置为空，请先配置！");
            throw new RuntimeException("缺少ES配置参数！");
        }

        List<HttpHost> httpHosts = new ArrayList<>();
        for (ElasticSearchProperties.EsAddress address : addressList) {
            String ip = address.getIp();
            String hostName = ip.split(":")[0];
            int port = Integer.parseInt(ip.split(":")[1]);
            HttpHost httpHost = new HttpHost(hostName, port, ElasticSearchProperties.PROTOCOL);
            httpHosts.add(httpHost);
        }
        HttpHost[] hosts = httpHosts.toArray(new HttpHost[addressList.size()]);
        RestClientBuilder builder = RestClient.builder(hosts);
        return new RestHighLevelClient(builder);
    }
}
